<template>
    <div>
        <div class="option_block">
            <el-row>
                <el-button type="success" icon="el-icon-plus" @click="openAddDialog">添加</el-button>
                <el-button type="primary" icon="el-icon-edit" @click="openEditDialog">修改</el-button>
                <el-button type="warning" icon="el-icon-setting" @click="openAuthDialog">授权</el-button>
                <el-button type="danger" icon="el-icon-setting" @click="resetPass">密码重置</el-button>
                <el-button type="warning" v-if="selectedRow && selectedRow.state == 0" icon="el-icon-refresh" @click="multeDelete">恢复</el-button>
                <el-button type="info" v-else icon="el-icon-delete" @click="multeDelete">禁用</el-button>
            </el-row>
        </div>
        <div class="content">
            <el-table ref="singleTable" highlight-current-row @current-change="handleRowChange" :data="list" v-loading="search.loading" id="form" height="666"
                      :row-class-name="tableRowClassName">
                <el-table-column prop="id" label="编号" width="66">
                </el-table-column>
                <el-table-column label="头像" width="120">
                    <template slot-scope="scope">
                        <el-avatar size="small" :src="scope.row.avatar"/>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="账户" width="120"></el-table-column>
                <el-table-column label="微信" width="120">
                    <template slot-scope="scope">{{ scope.row.nickName || '-' }}</template>
                </el-table-column>
                <el-table-column label="姓名" width="100">
                    <template slot-scope="scope">{{ scope.row.realName || '-' }}</template>
                </el-table-column>
                <el-table-column label="手机号">
                    <template slot-scope="scope">{{ scope.row.phone || '-' }}</template>
                </el-table-column>
                <el-table-column prop="companyName" label="所属公司" width="130">
                    <template slot-scope="scope">{{ scope.row.companyName || '-' }}</template>
                </el-table-column>
                <el-table-column prop="departmentName" label="所属部门" width="130">
                    <template slot-scope="scope">{{ scope.row.departmentName || '-' }}</template>
                </el-table-column>
                <el-table-column label="角色" width="160">
                    <template slot-scope="scope">{{ scope.row.role || '-' }}</template>
                </el-table-column>
                <el-table-column label="证件号" width="170">
                    <template slot-scope="scope">{{ scope.row.idNumber || '-' }}</template>
                </el-table-column>
                <el-table-column label="状态" width="60">
                    <template slot-scope="scope">
                        <icon-svg :icon="scope.row.state == 0 ? 'close1' : 'open_icon_successx'"></icon-svg>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" width="160">
                    <template slot-scope="scope">{{ scope.row.createdAt | parseTime }}</template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="search.page" :page-sizes="[1, 20, 30, 50,100]"
                           :page-size="search.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="search.total">
            </el-pagination>
        </div>

        <el-dialog :title="form.id ? '更新管理员信息' : '添加管理员信息'" :visible.sync="addFormVisible" width="60%">
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="账户" prop="name">
                    <el-input v-model="form.id" type="hidden" name="id" style="display:none;"></el-input>
                    <el-input v-model="form.name" name="name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="form.phone" name="phone" autocomplete="off" maxlength='11' show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="登录密码" prop="password" v-if="!form.id">
                    <el-input type="password" v-model="form.password" name="password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="所属公司" prop="company_id">
                    <el-select v-model="form.companyId" filterable remote reserve-keyword placeholder="搜索所属公司" :remote-method="searchCompanies" :loading="search.loading"
                               @change="loadDepartment">
                        <el-option v-for="item in company_list" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属部门" prop="department_id">
                    <el-select v-model="form.departmentId" filterable remote reserve-keyword placeholder="搜索部门" :remote-method="searchDepartment" :loading="search.loading">
                        <el-option v-for="item in department_list" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="姓名" prop="real_name">
                    <el-input v-model="form.realName" name="realName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="身份证号" prop="idNumber">
                    <el-input v-model="form.idNumber" name="idNumber" autocomplete="off" maxlength='18' show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="邮箱号" prop="email">
                    <el-input v-model="form.email" name="email" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="addFormVisible = false">关 闭</el-button>
            <el-button type="primary" @click="doSave">{{ form.id ? '更 新' : '添 加' }}</el-button>
        </span>
        </el-dialog>

        <el-dialog title="用户授权" :visible.sync="authFormVisible" :close-on-click-modal="false" width="66%">
            <el-form :model="authForm" ref="authForm" label-width="110px">
                <el-form-item label="用户昵称" prop="name">
                    <el-input v-model="authForm.id" type="hidden" style="display:none;"></el-input>
                    <el-input v-model="authForm.name" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="realName">
                    <el-input v-model="authForm.realName" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="所在公司及部门" prop="user_companies">
                    <el-input :value="(authForm.companyName|| '-') + ' / ' + (authForm.departmentName || '-')" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="授权角色" prop="roleList">
                    <el-checkbox-group v-model="authForm.roleList">
                        <el-checkbox v-for="role in role_list" :key="role.id" :label="role.id">{{ role.name }}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="authFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="authUpdate">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "index",
        data() {
            return {
                search: {page: 1, pageSize: 10, total: 0, loading: false},
                addFormVisible: false,
                authFormVisible: false,
                company: null,
                department: null,
                department_list: [],
                company_list: [],
                selectedRow: null,
                list: [],
                form: {departmentId: ''},
                authForm: {},
                role_list: [],
                rules: {
                    name: [{required: true, message: '请输入账户', trigger: 'blur'}],
                    phone: [{required: true, message: '请输入手机号', trigger: 'blur'}],
                    password: [{required: true, message: '请输入密码', trigger: 'blur'}],
                    realName: [{required: true, message: '请输入姓名', trigger: 'blur'}],
                    departmentId: [{required: true, message: '请选择所属部门', trigger: 'change'}],
                },
            };
        },
        mounted() {
            this.init();
        },
        methods: {
            doSave() {
                if (this.form.id) {
                    this.$confirm("确定修改管理员信息吗?").then(this.saveAdmin);
                } else {
                    this.saveAdmin();
                }
            },
            authUpdate() {
                const _this = this
                _this.$confirm('确定为此用户授权吗?', '').then(function () {
                    axios.post(basePath + '/admin/auth', _this.authForm).then(function (res) {
                        _this.$message({
                            message: res.msg,
                            type: res.success ? 'success' : 'error'
                        })
                        if (res.success) {
                            //添加成功
                            _this.authFormVisible = false
                            _this.authForm = {roleList: [],}
                            _this.init()
                        }
                    })
                })
            },
            saveAdmin() {
                const _this = this;
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        axios.post(basePath + '/admin/save', _this.form).then(function (res) {
                            _this.$message({
                                message: res.msg,
                                type: (res.success ? 'success' : 'error')
                            });
                            if (res.success) {
                                //添加成功
                                _this.$refs['form'].resetFields();
                                _this.addFormVisible = false;
                                _this.init();
                            }
                        });
                    } else {
                        return false;
                    }
                });
            },
            openAddDialog() {
                this.searchCompanies();
            },
            loadDepartment() {
                this.form.departmentId = '';
                this.searchDepartment();
            },
            searchCompanies(key) {
                //搜索客户公司
                const _this = this;
                axios.post(basePath + '/company/list', {key: key}).then(function (res) {
                    _this.company_list = res.data;
                    _this.addFormVisible = true;
                });
            },
            searchDepartment(key) {
                //加载客户部门
                const _this = this;
                if (_this.form.companyId) {
                    axios.post(basePath + '/company/departments/' + _this.form.companyId, {key: key}).then(function (res) {
                        _this.department_list = res.data;
                    });
                }
            },
            openEditDialog() {
                if (this.selectedRow) {
                    const _this = this;
                    axios.get(basePath + '/admin/info/' + this.selectedRow.id).then(function (res) {
                        if (res.success) {
                            _this.form = res.data;
                            _this.searchCompanies(res.data.companyName);
                            _this.searchDepartment(res.data.departmentName);
                            _this.addFormVisible = true;
                        }
                    });
                } else {
                    this.$message.error("请选择管理员进行操作");
                }
            },
            openAuthDialog() {
                const _this = this;
                if (_this.selectedRow) {
                    _this.addLoading = true;
                    //加载角色
                    axios.post(basePath + '/role/list', {pageSize: 50}).then(function (res) {
                        _this.role_list = res.data;
                    });
                    axios.get(basePath + '/admin/info/' + _this.selectedRow.id).then(function (res) {
                        if (res.success) {
                            _this.authForm = res.data;
                        } else {
                            _this.$message.error(res.msg);
                        }
                    });
                    _this.authFormVisible = true;
                    _this.addLoading = false;
                } else {
                    _this.$message.error('请选择要授权的用户');
                }
            },
            resetPass() {
                const _this = this;
                const validator = function (val) {
                    if (!val || val.length < 6) {
                        return '请输入一个6位以上的密码';
                    }
                    if (parseFloat(val) == val) {
                        return '密码不能为纯数字';
                    }
                }
                if (_this.selectedRow) {
                    this.$prompt('请输入新密码', '为 ' + _this.selectedRow.name + ' 重置密码', {
                        confirmButtonText: '确定修改',
                        inputPlaceholder: '建议密码不要太简单',
                        inputType: 'password',
                        cancelButtonText: '取消',
                        inputValidator: validator,
                    }).then(({value}) => {
                        _this.$confirm("确定要重置密码吗?").then(function () {
                            axios.post(basePath + '/admin/resetPass', {id: _this.selectedRow.id, password: value}).then(function (res) {
                                _this.$message({
                                    message: res.msg,
                                    type: res.success ? 'success' : 'error'
                                });
                            });
                        });
                    }).catch(() => {
                    });
                } else {
                    _this.$message.error('请选择要操作的用户');
                }
            },
            multeDelete() {
                const _this = this
                if (_this.selectedRow) {
                    _this.$confirm('确定要' + (_this.selectedRow.state == 0 ? '恢复' : '禁用') + '选中的用户吗?', '').then(function () {
                        axios.post(basePath + '/admin/delete', {
                            id: _this.selectedRow.id, state: (1 - _this.selectedRow.state)
                        })
                            .then(function (res) {
                                _this.$message({
                                    message: res.msg,
                                    type: res.success ? 'success' : 'error'
                                })
                                if (res.success) {
                                    _this.loading = true
                                    _this.init()
                                }
                            })
                    })
                } else {
                    _this.$message.error('请选择要禁用的用户');
                }
            },
            init() {
                const _this = this;
                this.search.loading = true;
                axios.post(basePath + '/admin/list', {departmentId: this.department_id, companyId: this.company_id}).then(function (res) {
                    //成功
                    _this.list = res.data;
                    _this.search.page = res.page
                    _this.search.total = res.total
                    _this.search.loading = false;
                });
            },
            handleRowChange(val) {
                this.selectedRow = val;
            },
            handleSizeChange(val) {
                this.search.pageSize = val;
                this.search.page = 1;
                this.init();
            },
            handleCurrentChange(val) {
                this.search.page = val;
                this.init();
            },
            tableRowClassName({row, rowIndex}) {
                if (row.state === 0) {
                    return 'danger-row';
                }
                return '';
            },
        }
    }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
</style>
